<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>车辆类型管理 - 铁路管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/admin/css/styles.css">
    <style>
        #app2 {
            display: flex;
            min-height: 100vh;
            width: 100%;
        }
    </style>
</head>
<body>
<div id="app2">
    <!-- 主内容区 -->
    <div class="main-content">



        <!-- 页面内容区域 -->
        <div id="page-content" style="padding: 0 20px;">
            <!-- 搜索和添加区域 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h3 class="card-title">车辆查询</h3>
                </div>
                <div class="card-body">
                    <form class="form-row" @submit.prevent="search">
                        <div class="form-group col-3">
                            <label for="trainNumber">车次号</label>
                            <input type="text" v-model="searchForm.trainNumber" class="form-control" id="trainNumber"
                                   placeholder="请输入车次号">
                        </div>
                        <div class="form-group col-3">
                            <label for="trainType">车型</label>
                            <select v-model="searchForm.trainType" class="form-control" id="trainType">
                                <option value="">全部</option>
                                <option value="G">高铁</option>
                                <option value="D">动车</option>
                            </select>
                        </div>
                        <div class="form-group col-3">
                            <label for="status">状态</label>
                            <select v-model="searchForm.status" class="form-control" id="status">
                                <option value="">全部</option>
                                <option value="1">运行中</option>
                                <option value="0">停运</option>
                            </select>
                        </div>
                        <div class="form-group col-3" style="display: flex; align-items: flex-end;">
                            <button type="submit" class="btn btn-primary" style="margin-right: 10px;">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button type="button" class="btn btn-success" @click="openModal('添加列车')">
                                <i class="fas fa-plus"></i> 添加列车
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 数据表格区域 -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">车辆列表</h3>
                </div>
                <div class="card-body">
                    <div class="table-container">
                        <table class="table">
                            <thead>
                            <tr>
                                <th>车辆ID</th>
                                <th>车辆号</th>
                                <th>车型</th>
                                <th>车厢数量</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>更新时间</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr v-for="item in paginatedData" :key="item.trainId">
                                <td>{{ item.trainId }}</td>
                                <td>{{ item.trainNumber || '-' }}</td>
                                <td>{{ item.trainType === 'G' ? 'G-高铁' : 'D-动车' }}</td>
                                <td>{{ item.carriageCount || '-' }}</td>
                                <td><span
                                        :class="{'badge badge-success': item.status === '1', 'badge badge-danger': item.status === '0'}">{{ item.status === 1 ? '运行中' : '停运' }}</span></td>
                                <td>{{ item.createTime || '-' }}</td>
                                <td>{{ item.updateTime || '-' }}</td>
                                <td>
                                    <button class="btn btn-primary btn-sm" @click="handleEdit(item)">
                                        <i class="fas fa-edit"></i> 编辑
                                    </button>
                                    <button class="btn btn-danger btn-sm" @click="handleDelete(item.trainId)">
                                        <i class="fas fa-trash"></i> 删除
                                    </button>
                                </td>
                            </tr>
                            <tr v-if="paginatedData.length === 0">
                                <td colspan="10" style="text-align: center;">暂无数据</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <!-- 分页区域 -->
                    <div class="pagination" style="margin-top: 20px; display: flex; justify-content: center; align-items: center;">
                        <button class="btn btn-sm" :disabled="currentPage === 1" @click="prevPage">&laquo;</button>

                        <span class="page-info" style="margin: 0 10px;">
                            第 {{ startIndex + 1 }}-{{ endIndex }} 条，共 {{ totalItems }} 条
                        </span>

                        <div class="page-numbers" style="display: flex; margin: 0 10px;">
                            <button v-for="page in pages" :key="page"
                                    class="btn btn-sm"
                                    :class="{ 'btn-primary': page === currentPage }"
                                    @click="goToPage(page)">
                                {{ page }}
                            </button>
                        </div>

                        <button class="btn btn-sm" :disabled="currentPage === totalPages" @click="nextPage">&raquo;</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="isModalVisible" class="modal"
         style="position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4);">
        <div class="modal-content"
             style="background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 600px; border-radius: 8px;">
            <div class="modal-header" style="padding: 10px 0; border-bottom: 1px solid #ddd; margin-bottom: 20px;">
                <h3>{{ currentModalTitle }}</h3>
                <span class="close"
                      style="color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer;"
                      @click="closeModal">&times;</span>
            </div>
            <form @submit.prevent="saveData">
                <input type="hidden" v-model="formData.trainId">
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="editTrainNumber">车次号 <span style="color: red;">*</span></label>
                        <input type="text" v-model="formData.trainNumber" class="form-control" id="editTrainNumber" required>
                    </div>
                    <div class="form-group col-6">
                        <label for="editTrainType">车型 <span style="color: red;">*</span></label>
                        <select v-model="formData.trainType" class="form-control" id="editTrainType" required>
                            <option value="G">G-高铁</option>
                            <option value="D">D-动车</option>
                            <option value="Z">Z-直达</option>
                            <option value="T">T-特快</option>
                            <option value="K">K-快速</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="editCarriageCount">车厢数量 <span style="color: red;">*</span></label>
                        <input type="number" v-model="formData.carriageCount" class="form-control" id="editCarriageCount" min="1" required>
                    </div>
                    <div class="form-group col-6">
                        <label for="editStatus">状态 <span style="color: red;">*</span></label>
                        <select v-model="formData.status" class="form-control" id="editStatus" required>
                            <option value="1">运行中</option>
                            <option value="0">停运</option>
                        </select>
                    </div>
                </div>
                <div class="form-group" style="margin-top: 20px;">
                    <button type="submit" class="btn btn-primary" style="margin-right: 10px;">保存</button>
                    <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="/admin/js/auth.js"></script>
<script src="/admin/js/jquery-3.6.0.js"></script>
<script src="/admin/js/vue.js"></script>
<script src="/admin/js/load-navbar.js"></script>
<script src="/admin/js/user-info.js"></script>
<script src="/admin/js/script.js"></script>
<script src="/admin/js/axios.js"></script>
<script src="/admin/js/config.js"></script>
<script>
    new Vue({
        el: '#app2',
        data: {
            searchForm: {
                trainNumber: '',
                trainType: '',
                status: ''
            },
            formData: {},
            tableData: [],
            isModalVisible: false,
            currentModalTitle: '',
            userName: '',

            // 分页相关数据
            currentPage: 1,
            pageSize: 8,
            totalItems: 0,
            // 控制是否使用前端分页
            useFrontendPagination: false
        },
        computed: {
            // 计算总页数
            totalPages() {
                return Math.ceil(this.totalItems / this.pageSize);
            },

            // 当前页显示的数据
            paginatedData() {
                return this.tableData;
            },

            // 显示的页码范围
            pages() {
                const pages = [];
                const maxVisiblePages = 5; // 最多显示5个页码
                let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
                if (endPage - startPage < maxVisiblePages - 1) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }
                for (let i = startPage; i <= endPage; i++) {
                    pages.push(i);
                }
                return pages;
            },

            // 当前页起始索引
            startIndex() {
                return (this.currentPage - 1) * this.pageSize;
            },

            // 当前页结束索引
            endIndex() {
                const end = this.startIndex + this.pageSize;
                return Math.min(end, this.totalItems);
            }
        },
        methods: {
            search() {
                console.log('搜索条件:', this.searchForm);
                this.currentPage = 1;  // 搜索时重置到第一页
                this.loadData();  // 调用loadData重新加载数据
            },
            openModal(title) {
                this.resetForm();
                this.currentModalTitle = title;
                this.isModalVisible = true;
            },
            closeModal() {
                this.isModalVisible = false;
                this.formData = {};
            },
            resetForm() {
                this.formData = {
                    trainId: '',
                    trainNumber: '',
                    trainType: 'G',
                    carriageCount: '',
                    status: '1'
                };
            },
            handleEdit(item) {
                this.formData = {...item};
                this.currentModalTitle = '编辑列车信息';
                this.isModalVisible = true;
            },
            handleDelete(id) {
                if (confirm(`确定要删除ID为 ${id} 的列车信息吗？`)) {
                    // 调用后端API删除数据
                    axios.delete("/admin/train_manage/delete/" + id)
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert('删除成功');
                                this.loadData(); // 重新加载数据
                            } else {
                                alert('删除失败: ' + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('删除请求失败:', error);
                            alert('删除失败，请重试');
                        });
                }
            },
            saveData() {
                // 验证逻辑保持不变
                if (!this.formData.trainNumber || !this.formData.trainType || !this.formData.carriageCount || !this.formData.status) {
                    alert('信息请输入完整！检查表单信息是否填写完全！！');
                    return;
                }
                console.log('保存数据:', this.formData);

                axios.post("/admin/train_manage/save", this.formData)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            alert('操作成功');
                            this.closeModal();
                            this.loadData();  // 保存后重新加载数据
                        } else {
                            alert('操作失败: ' + resp.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('保存请求失败:', error);
                        alert('操作失败，请重试');
                    });
            },
            // 分页方法
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.loadData();
                }
            },

            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.loadData();
                }
            },

            goToPage(page) {
                this.currentPage = page;
                this.loadData();
            },

            loadData() {
                axios.get("/admin/train_manage/getList", {
                    params: {
                        page: this.currentPage,
                        pageSize: this.pageSize,
                        trainNumber: this.searchForm.trainNumber || '',
                        trainType: this.searchForm.trainType || '',
                        status: this.searchForm.status || ''
                    }
                })
                    .then(resp => {
                        console.log('请求参数:', {currentPage: this.currentPage, pageSize: this.pageSize});
                        console.log('响应数据:', resp.data);

                        // 根据实际后端返回数据结构调整
                        if (resp.data.code === 200) {
                            // 确保数据格式正确
                            this.tableData = resp.data.data.list || [];
                            this.totalItems = resp.data.data.total || 0;
                        } else {
                            alert("加载数据失败: " + resp.data.message);
                            this.tableData = [];
                            this.totalItems = 0;
                        }
                    })
                    .catch(error => {
                        console.error("请求错误:", error);
                        alert("加载数据失败，请检查网络连接");
                        this.tableData = [];
                        this.totalItems = 0;
                    });
            }
        },
        mounted() {
            this.loadData();
        },
        created() {
            // 从localStorage获取用户名
            this.userName = localStorage.getItem('savedAdminName') || '用户';

            // 检查是否已登录（是否有token）
            const token = localStorage.getItem('saToken');
            if (!token) {
                // 如果没有token，跳转回登录页
                window.location.href = "/admin/login.html";
            }
        }
    });
</script>
</body>
</html>
